package integproject;

import java.net.*;
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;



public class Server {
	
	static String [] users = new String[10];
	static ArrayList<Handler> clients = new ArrayList<Handler>();
	
	public static void main(String[] args) throws Exception{
		ServerSocket socket = new ServerSocket(9999);
		Socket s = null;
		int clientCounter = 0;
		while(true){
			s = socket.accept();
			clientCounter++;
			Handler handle = new Handler(s);
                        clients.add(handle);
		}
		

	}
	
	static class Handler extends Thread{
		String name = "";
		BufferedReader read;
		PrintWriter write;
		
		public Handler(Socket s) throws Exception{
			read = new BufferedReader(new InputStreamReader(s.getInputStream()));
			write = new PrintWriter(s.getOutputStream(), true);
			start();
		}
                
		
		public void send(String message){
			write.println(message);
		}
		
		public void run(){
                        String input;
			try{
                                while(true){
                                        input = read.readLine();
                                        if(input.equalsIgnoreCase("GoodBye")){
                                                clients.remove(this);
                                                break;
                                        }
                                        sendToAll(input);
                                }
                        }
                        catch(Exception a){
                        
                        }
		}
	
	}
        
        public static void sendToAll(String input){
                for(Handler a : clients){
                        a.send(input);
                }
                
        }

}
